package org.dev4j.jdbc.custom;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import org.apache.log4j.Logger;

/**
 * Return sql files content
 * 
 * @author fuster
 * 
 */
public class SQLFilesFactory {

	private static final Logger logger = Logger.getLogger( SQLFilesFactory.class );
	private File currentFile;

	private SQLFilesFactory( String filePath ) {

		currentFile = new File( filePath );

	}

	/**
	 * Get one file content
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileContent( String filePath ) throws FileNotFoundException {

		logger.info( "Getting SQL file: [" + filePath + "]" );

		filePath = "/queries/" + filePath;
		String fileUrl = SQLFilesFactory.class.getResource( filePath ).toString().replace( "file:", "" );

		SQLFilesFactory ffactory = new SQLFilesFactory( fileUrl.toString() );
		return ffactory.readCompleteFile();

	}

	/**
	 * Get many file contents and join
	 * 
	 * @param files
	 * @return
	 */
	public static String getFileContent( String[] files ) throws FileNotFoundException {

		StringBuffer sb = new StringBuffer();

		for ( String s : files )
			sb.append( getFileContent( s ) );

		return sb.toString();

	}

	/**
	 * Private file scanner
	 * 
	 * @return
	 */
	private String readCompleteFile() throws FileNotFoundException {

		Scanner scanner = new Scanner( currentFile );

		StringBuffer sb = new StringBuffer();

		while ( scanner.hasNextLine() )
			sb.append( scanner.next() + " " );

		logger.info( "Returning this sql from file: " + sb.toString() );
		return sb.toString();

	}
}
